<template>
  <div>
    <h1>哈哈哈</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  methods: {
    timeout(ms) {
      return new Promise((resolve) => {
        setTimeout(resolve, ms, "done");
      });
    },

    oreder() {
      let promise = new Promise((resolve) => {
        console.log("new promisr");
        resolve();
      });

      promise.then(() => {
        console.log("promise 完成后输出");
      });
      console.log("哈哈哈");
    },

    init() {
      this.timeout(100).then((value) => {
        alert(value);
      });
    },

    loadImageAsync(url) {
      return new Promise((resolve, reject) => {
        const image = new Image();

        image.onload = () => {
          resolve(image);
        };
        image.onerror = () => {
          reject(new Error(`could not load at ${url}`));
        };

        image.src = url;
      });
    },
    log() {
      return new Promise((resolve) => {
        console.log(123);
        resolve;
      });
    },

    lianThenDemo() {
      this.log().then(() => {
        // console.log(456);
        console.log(456);
      });
    },

    // promise 的 catch 方法

    cathError() {
      const promise = new Promise(() => {
        throw new Error("errorhhahah ");
      });

      /* 
        .catch() 方法相当于 在.then 的方法的peomise 的第二个参数reject
      */
      promise.then(
        (data) => {
          console.log(data);
        },
        (error) => {
          console.log(error);
        }
      );

      promise.catch((error) => {
        console.log(error);
      });
    },

    promiseError() {
      const pro = new Promise((res) => {
        // res(x + 2);
        res();
      });
      pro.then(() => {
        console.log("promise可以吃掉错误");
      });

      setTimeout(() => {
        console.log("promise真的不难");
      }, 1000);
    },

    promiseError2() {
      const promise = new Promise(function (resolve, reject) {
        resolve("ok");
        setTimeout(function () {
          throw new Error("test");
        }, 0);
        reject("error");
      });
      promise.then(function (value) {
        console.log(value);
      });
      // .catch((error) => {
      //   console.log(error);
      // });
    },
  },
  created() {
    // this.init();
    // 如果是错误的图片地址就会报错
    this.loadImageAsync(
      "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=345443200,971142408&fm=26&gp=0.jpg"
    );

    this.lianThenDemo();

    this.cathError();

    // this.promiseError();

    this.promiseError2();
  },
  mounted() {},
  computed: {},
  watch: {},
};
</script>

<style>
</style>